package mylogger

import (
	"fmt"
	"path"
	"runtime"
	"strings"
	"time"
)

type Level uint16

const (
	UNKNOWN Level = iota
	DEBUG
	INFO
	WARNING
	ERROR
	FATAL
)

//往终端写日志

//Logger 日志对象
type Logger struct {
	LogLevel Level
}

func line(n int) (file string, line int) {
	_, file, line, ok := runtime.Caller(n)
	if !ok {
		fmt.Println("runtime err")
		return
	}
	file = path.Base(file)
	return file, line
}
func logLevel(msg string) Level {
	msg = strings.ToLower(msg)
	switch msg {
	case "debug":
		return DEBUG
	case "info":
		return INFO
	case "warn":
		return WARNING
	case "error":
		return ERROR
	case "fatal":
		return FATAL
	default:
		return UNKNOWN
	}
}

func (l Logger) compare(current Level) bool {
	return current >= l.LogLevel
}

// NewLog 构造函数
func NewLog(msg string) Logger {
	level := logLevel(msg)
	return Logger{
		LogLevel: level,
	}
}

//Debug 函数
func (l Logger) Debug(msg string) {
	if l.compare(DEBUG) {
		now := time.Now()
		date := now.Format("2006-01-02 15:04:05")
		fmt.Printf("[%s] [DEBUG] %s\n", date, msg)
	}

}

//Info 函数
func (l Logger) Info(msg string) {
	if l.compare(INFO) {
		now := time.Now()
		date := now.Format("2006-01-02 15:04:05")
		file, line := line(2)
		fmt.Printf("[%s] [INFO] %s 错误出现在文件:%s 第%d行\n", date, msg, file, line)
	}
}

//Warning 函数
func (l Logger) Warning(msg string) {
	if l.compare(WARNING) {
		now := time.Now()
		date := now.Format("2006-01-02 15:04:05")
		file, line := line(2)
		fmt.Printf("[%s] [WARNING] %s 错误出现在文件:%s 第%d行\n", date, msg, file, line)
	}
}

//Error 函数
func (l Logger) Error(msg string) {
	if l.compare(ERROR) {
		now := time.Now()
		date := now.Format("2006-01-02 15:04:05")
		file, line := line(2)
		fmt.Printf("[%s] [ERROR] %s 错误出现在文件:%s 第%d行\n", date, msg, file, line)
	}

}

//Fatal 函数
func (l Logger) Fatal(msg string) {
	if l.compare(FATAL) {
		now := time.Now()
		date := now.Format("2006-01-02 15:04:05")
		file, line := line(2)
		fmt.Printf("[%s] [Fatal] %s 错误出现在文件:%s 第%d行\n", date, msg, file, line)
	}
}
